/* mbed Microcontroller Library
 * Copyright (c) 2006-2013 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Ticker.h"

VTABLE(Ticker, TimerEvent)
    VMETHOD(Object, dtor) = (void (*)(Object *))&Ticker_dtor;
    VMETHOD(TimerEvent, dtor) = (void (*)(TimerEvent *))&Ticker_dtor;
    VMETHOD(Ticker, dtor) = (void (*)(Ticker *))&Ticker_dtor;
    VMETHOD(TimerEvent, onEvent) = (void (*)(TimerEvent *))&_Ticker_onEvent;
    VMETHOD(Ticker, onEvent) = (void (*)(Ticker *))&_Ticker_onEvent;
VTABLE_END

void Ticker_ctor(Ticker *obj) {
    _TimerEvent_ctor(&obj->super);
    VHOOK(Ticker);
    obj->_function = NULL;
}

void Ticker_dtor(Ticker *obj) {
    obj->_function = NULL;
    _TimerEvent_dtor(&obj->super);
}

void Ticker_attach(Ticker *obj, void (*func)(void), unsigned int millis) {
    obj->_function = func;
    _TimerEvent_remove(&obj->super);
    obj->_delay = millis;
    _TimerEvent_insert(&obj->super, millis);
}

void Ticker_detach(Ticker *obj) {
    _TimerEvent_remove(&obj->super);
    obj->_function = NULL;
}

void _Ticker_onEvent(Ticker *obj) {
    _TimerEvent_insert(&obj->super, obj->super._event.timestamp + obj->_delay);
    if(obj->_function != NULL) {
        obj->_function();
    }
}
